package cn.yiya.shiji.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.SingleBrandOrderActivity;
import cn.yiya.shiji.adapter.BrandsWorkAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MapRequest;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.OfficialTagsItem;
import cn.yiya.shiji.entity.TagProduceItem;
import cn.yiya.shiji.entity.TagProduceObject;

/**
 * Created by chenjian on 2015/10/18.
 */
public class BrandsWorkDetailFragment extends BaseFragment {
    private Handler mHandler;
    private RecyclerView mRecyclerView;
    private ArrayList<TagProduceItem> mLists;
    private int lastVisibleItemPosition;
    private int nOffset = 0;
    private int tagId = 0;
    private boolean isBottom;
    private TextView tvDefautNull;
    private View mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler(getActivity().getMainLooper());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.brands_work_detail, container, false);
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }

        initViews();
        initEvents();
        init();

        return mView;
    }

    @Override
    protected void initViews() {
        mRecyclerView = (RecyclerView)mView.findViewById(R.id.recycler_work_list);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        tvDefautNull = (TextView)mView.findViewById(R.id.tv_default_null);
    }

    @Override
    protected void initEvents() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                // 获取适配器的Item个数以及最后可见的Item
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                // 如果最后可见的Item比总数小1，表示最后一个，这里小3，预加载的意思
                if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE &&
                        (lastVisibleItemPosition) >= totalItemCount - 3) && !isBottom) {
                    loadMore();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                GridLayoutManager staggeredGridLayoutManager = (GridLayoutManager) layoutManager;
                lastVisibleItemPosition = staggeredGridLayoutManager.findLastCompletelyVisibleItemPosition();
            }
        });
    }

    @Override
    protected void init() {

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            if (mLists == null || mLists.size() == 0)
            initData();
        }
    }

    // 获取标签id，以及该Id下的推荐列表数据
    private void initData() {
        showPreDialog("正在加载中");
        nOffset = 0;
        isBottom = false;
        new RetrofitRequest<OfficialTagsItem>(ApiRequest.getApiShiji().getOfficialTagsList(
                ((SingleBrandOrderActivity) getActivity()).tagWork)).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    if (msg.obj != null) {
                        OfficialTagsItem item = (OfficialTagsItem) msg.obj;
                        tagId = item.getTag_id();
                        new RetrofitRequest<TagProduceObject>(ApiRequest.getApiShiji().tagStar(
                                MapRequest.setTagId(tagId, nOffset))).handRequest(new MsgCallBack() {
                            @Override
                            public void onResult(HttpMessage msg) {
                                if (msg.isSuccess()) {
                                    hidePreDialog();
//                                    setSuccessVIew(true);
                                    TagProduceObject item = (TagProduceObject) msg.obj;
                                    if (item != null) {
                                        mLists = item.list;
                                        if(mLists != null && mLists.size() > 0) {
                                            isBottom = false;
                                            mRecyclerView.setAdapter(new BrandsWorkAdapter(mLists, getActivity()));
                                            tvDefautNull.setVisibility(View.GONE);
                                        }else {
                                            if(nOffset == 0) {
                                                tvDefautNull.setVisibility(View.VISIBLE);
                                            }
                                        }
                                    }
                                } else {
                                    hidePreDialog();
                                }
                            }
                        });
                    } else {
//                        setSuccessVIew(false);
                        hidePreDialog();
                    }
                } else {
//                    setSuccessVIew(false);
                    hidePreDialog();
                }
            }
        });
    }

    private void loadMore() {
        nOffset += 10;
        new RetrofitRequest<TagProduceObject>(ApiRequest.getApiShiji().tagStar(
        MapRequest.setTagId(tagId, nOffset))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    TagProduceObject item = (TagProduceObject) msg.obj;
                    if (item != null && item.list.size() > 0) {
                        mLists.addAll(item.list);
                        mRecyclerView.getAdapter().notifyDataSetChanged();
                    } else {
                        isBottom = true;
                    }
                }
            }
        });
    }
}
